import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import type { UserInfo } from '@/api/user'
import { getUserInfo } from '@/api/user'
import router from '@/router'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)
  const isLoggedIn = computed(() => !!token.value)

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 设置用户信息
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) return

    try {
      const info = await getUserInfo()
      setUserInfo(info)
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
    }
  }

  // 登录
  const login = (newToken: string, info: UserInfo) => {
    setToken(newToken)
    setUserInfo(info)
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    router.push('/login')
  }

  // 检查登录状态
  const checkAuth = () => {
    if (!token.value) {
      router.push('/login')
      return false
    }
    return true
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    setToken,
    setUserInfo,
    fetchUserInfo,
    login,
    logout,
    checkAuth
  }
})